<template>
  <el-table :data="bannerList" style="width: 100%" v-loading="loading">
    <el-table-column prop="bannerid" label="轮播图编号" width="180" />
    <el-table-column prop="date" label="图片" width="180">
      <template #default="scope">
        <img class="img" :src="scope.row.img" />
      </template>
    </el-table-column>
    <el-table-column prop="alt" label="图片提示" width="180" />
    <el-table-column prop="link" label="图片链接" />
    <el-table-column prop="address" label="是否启用" v-if="crud.charAt(2)==='1'">
      <template #default="scope">
        <el-switch v-model="scope.row.flag" @change="(val: boolean) => updateBannerFlag(scope.row.bannerid, val)" />
      </template>
    </el-table-column>
    <el-table-column prop="address" label="是否删除" v-if="crud.charAt(3)==='1'">
      <template #default="scope">
        <el-popconfirm
    confirm-button-text="是的"
    cancel-button-text="否"
    title="您确定要删除吗?"
    hide-icon="true"
    @confirm="deletes(scope.row.bannerid)">
    <template #reference>
      <el-button type="danger">删除</el-button>
    </template>
  </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
</template>
<script setup lang="ts">
import { reactive,ref } from 'vue'
import service from "../../../until/service";
import { ElMessage } from 'element-plus'
import {useRoute} from "vue-router";
import 'element-plus/dist/index.css';
import {useRouteStore} from "../../../piniaStore/index"
const routeStore = useRouteStore();
const loading = ref(routeStore.loading)
const $route = useRoute();
const crud:string = ($route.meta.crud as string);
interface Banners {
  link: string,
  img: string,
  alt: string,
  bannerid: string,
  flag: boolean
}
let bannerList = reactive<Banners[]>([]);
// 获取轮播图数据
const getBanners = () => {
  loading.value = true

  service({
    url: "/banner/list",

  }).then((res: any) => {
    if (res.data.code == '200') {
      bannerList.push(...res.data.data)
    loading.value = false

    }
  })

}
// 修改轮播图状态
const updateBannerFlag = (bannerid: string, val: boolean) => {
  service({
    url: "/banner/updateFlag",
    method: 'post',
    data: {
      bannerid: bannerid,
      flag: val
    }
  }).then(res => {
    if (res.data.code == '200') {
    loading.value = false
      console.log('更新成功')
    }
  })

}
// 删除轮播图
const deletes = (bnnerid: string) => {
  loading.value = true

  service({
    url: "/banner/delete",
    method: 'get',
    params: {
      bannerid: bnnerid
    }
  }).then(res => {
    if (res.data.code == '200') {
      console.log('删除成功')
    loading.value = false

      bannerList.find((element, item) => {
        if (element.bannerid == bnnerid) {
          bannerList.splice(item, 1)
        }
      });
      ElMessage({
    message: '删除成功',
    type: 'success',
  })
    }
  })

}
getBanners()
</script>
<style scoped>
.img {
  width: 200px;
  height: 150px;
}
</style>